/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.admin.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.protobuf.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;

import javax.validation.Valid;

import lombok.extern.slf4j.Slf4j;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.modules.admin.entity.MaintainPlanContentUser;
import org.springblade.modules.admin.entity.MaintainSign;
import org.springblade.modules.admin.entity.UserTrajectory;
import org.springblade.modules.admin.enums.WxArriveStatusEnums;
import org.springblade.modules.admin.service.IMaintainPlanContentUserService;
import org.springblade.modules.admin.service.IMaintainSignService;
import org.springblade.modules.admin.service.IUserTrajectoryService;
import org.springblade.modules.admin.utils.MapUtil;
import org.springblade.modules.admin.vo.plan.PlanMaintainUserVO;
import org.springblade.modules.admin.vo.plan.wx.WxYjSendMsgVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springblade.modules.admin.entity.MaintainWxmsgType;
import org.springblade.modules.admin.service.IMaintainWxmsgTypeService;
import org.springblade.core.boot.ctrl.BladeController;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * 控制器
 *
 * @author ysq
 * @since 2024-11-05
 */
@RestController
@AllArgsConstructor
@RequestMapping("admin/wx/msg/type")
@Api(value = "维修预警设置", tags = "维修预警设置")
@Slf4j
public class MaintainWxmsgTypeController extends BladeController {

	private final IMaintainWxmsgTypeService maintainWxmsgTypeService;

	private final IMaintainPlanContentUserService planContentUserService;
	private final IMaintainSignService maintainSignService;
	private final IUserTrajectoryService userTrajectoryService;;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入maintainWxmsgType")
	public R<MaintainWxmsgType> detail() {
		return R.data(maintainWxmsgTypeService.detail(AuthUtil.getTenantId()));
	}

	/**
	 * 新增
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入maintainWxmsgType")
	public R save(@Valid @RequestBody MaintainWxmsgType maintainWxmsgType) {
		return R.status(maintainWxmsgTypeService.saveOrUpdate(maintainWxmsgType));
	}


	/**
	 * 发送维修预警消息
	 *
	 * @param message type 值说明
	 *                1:当指派人员10分钟后移动没有超过500米
	 *                2：当人员距离达到目的地剩余30%时提醒
	 *                3:超出预计时间未到达
	 */
	@PostMapping("/test")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "test", notes = "test")
	public R test( String message) throws ServiceException {
		JSONObject jsonObject = JSONObject.parseObject(message);
		log.info("===============接收维修预警消息====================");
		log.info("接收时间:[{}],接受内容:[{}]", LocalDateTime.now(), message);
		JSONObject parseObject = JSON.parseObject(message);
		WxYjSendMsgVo wxYjSendMsgVo = JSON.parseObject(parseObject.get("wx_yj_msg").toString(), WxYjSendMsgVo.class);
		List<PlanMaintainUserVO> maintainUserList = wxYjSendMsgVo.getMaintainUserList();
		Integer type = wxYjSendMsgVo.getType();
		MaintainWxmsgType detail = maintainWxmsgTypeService.detail(wxYjSendMsgVo.getTenantId());
		List<MaintainPlanContentUser> planContentUserList = planContentUserService.list(Wrappers.<MaintainPlanContentUser>lambdaQuery().eq(MaintainPlanContentUser::getPlanId, wxYjSendMsgVo.getPlanId()));
		if (type == 1) {
			//1:当指派人员10分钟后移动没有超过500米
			for (PlanMaintainUserVO planMaintainUserVO : maintainUserList) {
				UserTrajectory userTrajectory = userTrajectoryService.getOne(Wrappers.<UserTrajectory>lambdaQuery().between(UserTrajectory::getCreateTime, DateUtil.beginOfDay(new Date()), new Date()).eq(UserTrajectory::getUserId, planMaintainUserVO.getMaintainUserId()).orderByDesc(UserTrajectory::getCreateTime).last("limit 1"));
				int distance = MapUtil.getDistance(MapUtil.getLongitude(planMaintainUserVO.getLongitude()), MapUtil.getLatitude(planMaintainUserVO.getLatitude()), MapUtil.getLongitude(userTrajectory.getLongitude()), MapUtil.getLatitude(userTrajectory.getLatitude()));
				for (MaintainPlanContentUser maintainPlanContentUser : planContentUserList) {
					if (maintainPlanContentUser.getUserId().equals(planMaintainUserVO.getMaintainUserId())) {
						if (distance <= Convert.toInt(detail.getMoveKm().multiply(Convert.toBigDecimal(1000)))) {
							maintainPlanContentUser.setWxArriveStatus(WxArriveStatusEnums.NO_MOVE.getId());
						}
					}
				}
			}
		} else if (type == 2) {
			//2：当人员距离达到目的地剩余30%时提醒
			for (PlanMaintainUserVO planMaintainUserVO : maintainUserList) {
				for (MaintainPlanContentUser maintainPlanContentUser : planContentUserList) {
					if (maintainPlanContentUser.getUserId().equals(planMaintainUserVO.getMaintainUserId())) {
						maintainPlanContentUser.setWxArriveStatus(WxArriveStatusEnums.ABOUT_ARRIVE_ON_TIME.getId());
					}
				}
			}
		} else if (type == 3) {
			// 3:超出预计时间未到达
			MaintainSign maintainSign = maintainSignService.getOne(Wrappers.<MaintainSign>lambdaQuery().eq(MaintainSign::getPlanId, wxYjSendMsgVo.getPlanId()).orderByAsc(MaintainSign::getCreateTime).last("limit 1"));
			for (PlanMaintainUserVO planMaintainUserVO : maintainUserList) {
				for (MaintainPlanContentUser maintainPlanContentUser : planContentUserList) {
					if (maintainPlanContentUser.getUserId().equals(planMaintainUserVO.getMaintainUserId())) {
						if (maintainSign == null || maintainSign.getSignTime() == null) {
							maintainPlanContentUser.setWxArriveStatus(WxArriveStatusEnums.DIS_ARRIVE_ON_TIME_NO_SIGN.getId());
						}
					}
				}
			}
		}
		planContentUserService.updateBatchById(planContentUserList);
		return R.data(true);
	}
}
